package com.kevin.serial;

import com.kevin.Entity.MessageRecord;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

@Slf4j
public class MessageRecordEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        MessageRecord messageRecord = (MessageRecord) o ;
        log.info("MessageRecordEncoder   start");
        byteBuf.writeLong(messageRecord.getHeader().getSessionId());
        byteBuf.writeByte(messageRecord.getHeader().getOptCode());
        Object body = messageRecord.getBody();
        if(null!=body){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(body);
            byte[] bytes= bos.toByteArray();//
            byteBuf.writeInt(bytes.length); //写消息的长度
            byteBuf.writeBytes(bytes);
        }else{
            byteBuf.writeInt(0);
        }
    }
}
